<template>
  <div class="points-goods">
    <el-card>
      <div class="header">
        <span></span>
        <el-button type="primary" @click="openGoodsDialog('add')">新增商品</el-button>
      </div>
      <el-form :inline="true" :model="filter" class="filter-bar" label-width="90px" style="margin-bottom: 16px;">
        <el-form-item label="商品名称">
          <el-input v-model="filter.name" placeholder="商品名称/平台ID" clearable style="width: 180px;" />
        </el-form-item>
        <el-form-item label="商品类型">
          <el-select v-model="filter.type" clearable style="width: 140px;">
            <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="上架状态">
          <el-select v-model="filter.status" clearable style="width: 120px;">
            <el-option label="上架" value="上架" />
            <el-option label="下架" value="下架" />
          </el-select>
        </el-form-item>
        <div class="filter-actions-row">
          <el-button type="primary" @click="doFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
          <el-button @click="refresh">刷新</el-button>
          <el-button type="primary" @click="exportGoods">导出</el-button>
        </div>
      </el-form>

      <!-- 批量操作按钮组 -->
      <div class="batch-actions" style="margin-bottom: 12px; display: flex; gap: 12px; align-items: center;">
        <el-button :disabled="!multipleSelection.length" @click="batchUp">批量上架</el-button>
        <el-button :disabled="!multipleSelection.length" @click="batchDown">批量下架</el-button>
        <el-button :disabled="!multipleSelection.length" @click="batchExport">批量导出</el-button>
        <el-button type="danger" :disabled="!multipleSelection.length" @click="batchDelete">批量删除</el-button>
        <el-button style="margin-left: auto;" @click="showFieldsDialog = true">字段显示</el-button>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        :default-sort="{prop: 'createdAt', order: 'descending'}"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="48" />
        <el-table-column v-if="fieldsVisible.id" prop="id" label="商品ID" width="100" />
        <el-table-column v-if="fieldsVisible.image" prop="image" label="图片" width="80">
          <template #default="scope">
            <el-image :src="scope.row.image" style="width: 48px; height: 48px; object-fit: cover;" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column v-if="fieldsVisible.name" prop="name" label="商品名称" width="160" />
        <el-table-column v-if="fieldsVisible.platformId" prop="platformId" label="平台ID" width="100" />
        <el-table-column v-if="fieldsVisible.type" prop="type" label="商品类型" width="100" />
        <el-table-column v-if="fieldsVisible.points" prop="points" label="所需积分" width="100" />
        <el-table-column v-if="fieldsVisible.amount" prop="amount" label="所需金额(元)" width="110" />
        <el-table-column v-if="fieldsVisible.total" prop="total" label="总数" width="100" />
        <el-table-column v-if="fieldsVisible.stock" prop="stock" label="剩余库存" width="100" />
        <el-table-column v-if="fieldsVisible.limit" prop="limit" label="兑换上限" width="100" />
        <el-table-column v-if="fieldsVisible.status" prop="status" label="上架状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === '上架' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column v-if="fieldsVisible.validity" prop="validity" label="兑换有效期" width="140" />
        <el-table-column v-if="fieldsVisible.sort" prop="sort" label="排序" width="80" />
        <el-table-column v-if="fieldsVisible.createdAt" prop="createdAt" label="创建时间" width="140" />
        <el-table-column v-if="fieldsVisible.updatedAt" prop="updatedAt" label="更新时间" width="140" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="showDetail(scope.row)">详情</el-button>
            <el-button size="small" @click="editGoods(scope.row)">编辑</el-button>
            <el-button size="small" type="warning" @click="toggleStatus(scope.row)">
              {{ scope.row.status === '上架' ? '下架' : '上架' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteGoods(scope.row)">删除</el-button>
            <el-button size="small" @click="openRecordDialog(scope.row)">兑换记录</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="page.total"
        layout="total, prev, pager, next, sizes"
        :page-sizes="[10, 20, 50, 100]"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>
  </div>

  <!-- 商品详情弹窗 -->
  <el-dialog v-model="detailDialog.visible" title="商品详情" width="500px" :close-on-click-modal="false">
    <template #default>
      <el-descriptions :column="1" border v-if="detailDialog.data">
        <el-descriptions-item label="商品ID">{{ detailDialog.data.id }}</el-descriptions-item>
        <el-descriptions-item label="图片">
          <el-image :src="detailDialog.data.image" style="width: 80px; height: 80px; object-fit: cover;" fit="cover" />
        </el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ detailDialog.data.name }}</el-descriptions-item>
        <el-descriptions-item label="平台ID">{{ detailDialog.data.platformId }}</el-descriptions-item>
        <el-descriptions-item label="商品类型">{{ detailDialog.data.type }}</el-descriptions-item>
        <el-descriptions-item label="所需积分">{{ detailDialog.data.points }}</el-descriptions-item>
        <el-descriptions-item label="所需金额">{{ detailDialog.data.amount }}</el-descriptions-item>
        <el-descriptions-item label="总数">{{ detailDialog.data.total }}</el-descriptions-item>
        <el-descriptions-item label="剩余库存">{{ detailDialog.data.stock }}</el-descriptions-item>
        <el-descriptions-item label="兑换上限">{{ detailDialog.data.limit }}</el-descriptions-item>
        <el-descriptions-item label="上架状态">
          <el-tag :type="detailDialog.data.status === '上架' ? 'success' : 'info'">{{ detailDialog.data.status }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="兑换有效期">{{ detailDialog.data.validity }}</el-descriptions-item>
        <el-descriptions-item label="排序">{{ detailDialog.data.sort }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailDialog.data.createdAt }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailDialog.data.updatedAt }}</el-descriptions-item>
      </el-descriptions>
    </template>
    <template #footer>
      <el-button @click="detailDialog.visible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 新增/编辑商品弹窗 -->
  <el-dialog v-model="goodsDialog.visible" :title="goodsDialog.mode === 'add' ? '新增商品' : '编辑商品'" width="500px" :close-on-click-modal="false">
    <el-form :model="goodsDialog.form" :rules="goodsRules" ref="goodsFormRef" label-width="100px" style="margin-top: 12px;">
      <el-form-item label="商品图片" prop="image">
        <el-input v-model="goodsDialog.form.image" placeholder="图片URL（mock上传）" />
      </el-form-item>
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goodsDialog.form.name" />
      </el-form-item>
      <el-form-item label="平台ID" prop="platformId">
        <el-input v-model="goodsDialog.form.platformId" />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-select v-model="goodsDialog.form.type" style="width: 100%">
          <el-option v-for="item in typeOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="所需积分" prop="points">
        <el-input-number v-model="goodsDialog.form.points" :min="0" style="width: 100%" />
      </el-form-item>
      <el-form-item label="所需金额(元)" prop="amount">
        <el-input-number v-model="goodsDialog.form.amount" :min="0" :step="0.01" style="width: 100%" />
      </el-form-item>
      <el-form-item label="总数" prop="total">
        <el-input-number v-model="goodsDialog.form.total" :min="1" style="width: 100%" />
      </el-form-item>
      <el-form-item label="剩余库存" prop="stock">
        <el-input-number v-model="goodsDialog.form.stock" :min="0" :max="goodsDialog.form.total || 1" style="width: 100%" />
      </el-form-item>
      <el-form-item label="兑换上限" prop="limit">
        <el-input-number v-model="goodsDialog.form.limit" :min="0" style="width: 100%" />
      </el-form-item>
      <el-form-item label="上架状态" prop="status">
        <el-select v-model="goodsDialog.form.status" style="width: 100%">
          <el-option label="上架" value="上架" />
          <el-option label="下架" value="下架" />
        </el-select>
      </el-form-item>
      <el-form-item label="兑换有效期" prop="validity">
        <el-date-picker v-model="goodsDialog.form.validity" type="date" value-format="YYYY-MM-DD" style="width: 100%" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="goodsDialog.form.sort" :min="1" style="width: 100%" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="goodsDialog.visible = false">取消</el-button>
      <el-button type="primary" @click="submitGoods">保存</el-button>
    </template>
  </el-dialog>

  <!-- 字段自定义显示弹窗 -->
  <el-dialog v-model="showFieldsDialog" title="自定义字段显示" width="400px" :close-on-click-modal="false">
    <el-checkbox-group v-model="fieldsChecked">
      <el-checkbox v-for="item in fieldsOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="showFieldsDialog = false">取消</el-button>
      <el-button type="primary" @click="saveFields">保存</el-button>
    </template>
  </el-dialog>

  <!-- 兑换记录弹窗 -->
  <el-dialog v-model="recordDialog.visible" title="兑换记录" width="700px" :close-on-click-modal="false">
    <el-table :data="recordDialog.tableData" style="width: 100%">
      <el-table-column prop="orderNo" label="订单号" width="140">
        <template #default="scope">
          <el-link type="primary" @click="openOrderDialog(scope.row)">{{ scope.row.orderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="orderStatus" label="订单状态" width="100" />
      <el-table-column prop="member" label="会员昵称/ID" width="180" />
      <el-table-column prop="exchangeTime" label="兑换时间" width="180" />
      <el-table-column prop="quantity" label="兑换数量" width="100" />
    </el-table>
    <el-pagination
      v-model:current-page="recordDialog.page.current"
      v-model:page-size="recordDialog.page.size"
      :total="recordDialog.page.total"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[5, 10, 20]"
      style="margin-top: 16px; text-align: right;"
      @current-change="loadRecordPage"
      @size-change="loadRecordPage"
    />
    <template #footer>
      <el-button @click="recordDialog.visible = false">关闭</el-button>
    </template>
  </el-dialog>

  <!-- 订单详情弹窗 -->
  <el-dialog v-model="orderDialog.visible" title="订单详情" width="500px" :close-on-click-modal="false">
    <el-descriptions :column="1" border v-if="orderDialog.data">
      <el-descriptions-item label="订单号">{{ orderDialog.data.orderNo }}</el-descriptions-item>
      <el-descriptions-item label="订单状态">{{ orderDialog.data.orderStatus }}</el-descriptions-item>
      <el-descriptions-item label="会员">{{ orderDialog.data.member }}</el-descriptions-item>
      <el-descriptions-item label="兑换时间">{{ orderDialog.data.exchangeTime }}</el-descriptions-item>
      <el-descriptions-item label="兑换数量">{{ orderDialog.data.quantity }}</el-descriptions-item>
      <el-descriptions-item label="商品ID">{{ orderDialog.data.goodsId }}</el-descriptions-item>
      <!-- 可扩展更多字段，如收货信息、金额等 -->
    </el-descriptions>
    <template #footer>
      <el-button @click="orderDialog.visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElForm } from 'element-plus'

const typeOptions = ['实物', '虚拟', '优惠券']

const filter = reactive({
  name: '',
  type: '',
  status: ''
})

const allData = ref([
  {
    id: 'G001', image: 'https://img.yzcdn.cn/vant/cat.jpeg', name: '蓝牙耳机', platformId: 'PLT001', type: '实物', points: 1200, amount: 0, total: 100, stock: 50, limit: 2, status: '上架', validity: '2024-12-31', sort: 1, createdAt: '2024-06-01', updatedAt: '2024-06-10'
  },
  {
    id: 'G002', image: 'https://img.yzcdn.cn/vant/cat.jpeg', name: '50元优惠券', platformId: 'PLT002', type: '优惠券', points: 500, amount: 0, total: 200, stock: 100, limit: 1, status: '下架', validity: '2024-12-31', sort: 2, createdAt: '2024-06-02', updatedAt: '2024-06-09'
  },
  {
    id: 'G003', image: 'https://img.yzcdn.cn/vant/cat.jpeg', name: '小米手环', platformId: 'PLT003', type: '实物', points: 800, amount: 0, total: 50, stock: 30, limit: 1, status: '上架', validity: '2024-12-31', sort: 3, createdAt: '2024-06-03', updatedAt: '2024-06-08'
  },
  {
    id: 'G004', image: 'https://img.yzcdn.cn/vant/cat.jpeg', name: '视频会员月卡', platformId: 'PLT004', type: '虚拟', points: 300, amount: 0, total: 500, stock: 200, limit: 3, status: '上架', validity: '2024-12-31', sort: 4, createdAt: '2024-06-04', updatedAt: '2024-06-07'
  }
])

const page = reactive({ current: 1, size: 10, total: 0 })

const tableData = computed(() => {
  let data = allData.value
  if (filter.name) {
    data = data.filter(row => row.name.includes(filter.name) || row.platformId.includes(filter.name))
  }
  if (filter.type) {
    data = data.filter(row => row.type === filter.type)
  }
  if (filter.status) {
    data = data.filter(row => row.status === filter.status)
  }
  page.total = data.length
  const startIdx = (page.current - 1) * page.size
  return data.slice(startIdx, startIdx + page.size)
})

const detailDialog = reactive({ visible: false, data: null as any })
function showDetail(row: Record<string, any>) {
  detailDialog.data = { ...row }
  detailDialog.visible = true
}

function doFilter() {
  page.current = 1
}
function resetFilter() {
  filter.name = ''
  filter.type = ''
  filter.status = ''
  page.current = 1
}
function refresh() {
  ElMessage.success('已刷新（mock）')
}
function exportGoods() {
  ElMessage.success('导出成功（mock）')
}

const goodsDialog = reactive({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    id: '', image: '', name: '', platformId: '', type: '', points: 0, amount: 0, total: 1, stock: 0, limit: 0, status: '上架', validity: '', sort: 1
  }
})
const goodsFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const goodsRules = {
  image: [{ required: true, message: '请填写图片URL', trigger: 'blur' }],
  name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  platformId: [{ required: true, message: '请输入平台ID', trigger: 'blur' }],
  type: [{ required: true, message: '请选择商品类型', trigger: 'change' }],
  points: [
    { required: true, message: '请输入所需积分', trigger: 'blur' },
    { validator: (rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error('所需积分必须大于0'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  amount: [{ required: false }],
  total: [
    { required: true, message: '请输入总数', trigger: 'blur' },
    { validator: (rule: any, value: number, callback: any) => {
        if (value <= 0) {
          callback(new Error('总数必须大于0'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入剩余库存', trigger: 'blur' },
    { validator: (rule: any, value: number, callback: any) => {
        if (value < 0) {
          callback(new Error('剩余库存不能小于0'))
        } else if (value > goodsDialog.form.total) {
          callback(new Error('剩余库存不能大于总数'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  limit: [{ required: true, message: '请输入兑换上限', trigger: 'blur' }],
  status: [{ required: true, message: '请选择上架状态', trigger: 'change' }],
  validity: [{ required: true, message: '请选择有效期', trigger: 'change' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
}
function openGoodsDialog(mode: 'add' | 'edit', row?: Record<string, any>) {
  goodsDialog.mode = mode
  if (mode === 'add') {
    Object.assign(goodsDialog.form, { id: '', image: '', name: '', platformId: '', type: '', points: 0, amount: 0, total: 1, stock: 0, limit: 0, status: '上架', validity: '', sort: 1 })
  } else if (row) {
    Object.assign(goodsDialog.form, { ...row })
  }
  goodsDialog.visible = true
  nextTick(() => goodsFormRef.value?.clearValidate())
}
function addGoods() {
  openGoodsDialog('add')
}
function editGoods(row: Record<string, any>) {
  openGoodsDialog('edit', row)
}
function submitGoods() {
  goodsFormRef.value?.validate((valid: boolean) => {
    if (!valid) return
    // 不再允许只填金额，所需积分必须大于0，amount可为0或大于0
    // 其他逻辑不变
    if (goodsDialog.mode === 'add') {
      // mock 新增
      const newId = 'G' + (Math.floor(Math.random() * 9000) + 1000)
      allData.value.unshift({ ...goodsDialog.form, id: newId, createdAt: new Date().toISOString().slice(0, 10), updatedAt: new Date().toISOString().slice(0, 10) })
      ElMessage.success('新增成功（mock）')
    } else {
      // mock 编辑
      const idx = allData.value.findIndex(item => item.id === goodsDialog.form.id)
      if (idx > -1) {
        allData.value[idx] = {
          ...goodsDialog.form,
          createdAt: allData.value[idx].createdAt,
          updatedAt: new Date().toISOString().slice(0, 10)
        }
        ElMessage.success('编辑成功（mock）')
      }
    }
    goodsDialog.visible = false
  })
}
function toggleStatus(row: Record<string, any>) {
  row.status = row.status === '上架' ? '下架' : '上架'
  ElMessage.success('状态已更新')
}
function deleteGoods(row: Record<string, any>) {
  allData.value = allData.value.filter(item => item.id !== row.id)
  ElMessage.success('删除成功')
}

const multipleSelection = ref<any[]>([])
function handleSelectionChange(val: any[]) {
  multipleSelection.value = val
}
function batchUp() {
  if (!multipleSelection.value.length) return
  multipleSelection.value.forEach(row => {
    row.status = '上架'
  })
  ElMessage.success('批量上架成功（mock）')
}
function batchDown() {
  if (!multipleSelection.value.length) return
  multipleSelection.value.forEach(row => {
    row.status = '下架'
  })
  ElMessage.success('批量下架成功（mock）')
}
function batchExport() {
  if (!multipleSelection.value.length) return
  ElMessage.success('批量导出成功（mock）')
}
function batchDelete() {
  if (!multipleSelection.value.length) return
  ElMessageBox.confirm('确定要删除选中的商品吗？', '批量删除', { type: 'warning' })
    .then(() => {
      const ids = multipleSelection.value.map(row => row.id)
      allData.value = allData.value.filter(item => !ids.includes(item.id))
      ElMessage.success('批量删除成功（mock）')
      multipleSelection.value = []
    })
    .catch(() => {})
}

const fieldsOptions = [
  { label: '商品ID', value: 'id' },
  { label: '图片', value: 'image' },
  { label: '商品名称', value: 'name' },
  { label: '平台ID', value: 'platformId' },
  { label: '商品类型', value: 'type' },
  { label: '所需积分', value: 'points' },
  { label: '所需金额', value: 'amount' },
  { label: '总数', value: 'total' },
  { label: '剩余库存', value: 'stock' },
  { label: '兑换上限', value: 'limit' },
  { label: '上架状态', value: 'status' },
  { label: '兑换有效期', value: 'validity' },
  { label: '排序', value: 'sort' },
  { label: '创建时间', value: 'createdAt' },
  { label: '更新时间', value: 'updatedAt' }
]
const defaultFields = fieldsOptions.map(f => f.value)
const FIELDS_KEY = 'points_goods_fields'
const showFieldsDialog = ref(false)
const fieldsChecked = ref<string[]>([])
const fieldsVisible = reactive<Record<string, boolean>>({})

function updateFieldsVisible() {
  fieldsOptions.forEach(f => {
    fieldsVisible[f.value] = fieldsChecked.value.includes(f.value)
  })
}
function saveFields() {
  localStorage.setItem(FIELDS_KEY, JSON.stringify(fieldsChecked.value))
  updateFieldsVisible()
  showFieldsDialog.value = false
}
onMounted(() => {
  const saved = localStorage.getItem(FIELDS_KEY)
  if (saved) {
    fieldsChecked.value = JSON.parse(saved)
  } else {
    fieldsChecked.value = [...defaultFields]
  }
  updateFieldsVisible()
})
watch(fieldsChecked, updateFieldsVisible)

const mockRecords = [
  { goodsId: 'G001', orderNo: 'O20240610001', orderStatus: '已完成', member: '张三/1001', exchangeTime: '2024-06-10 10:00', quantity: 1 },
  { goodsId: 'G001', orderNo: 'O20240611002', orderStatus: '已完成', member: '李四/1002', exchangeTime: '2024-06-11 14:20', quantity: 2 },
  { goodsId: 'G002', orderNo: 'O20240612003', orderStatus: '已取消', member: '王五/1003', exchangeTime: '2024-06-12 09:30', quantity: 1 },
  { goodsId: 'G001', orderNo: 'O20240613004', orderStatus: '待发货', member: '赵六/1004', exchangeTime: '2024-06-13 16:45', quantity: 1 },
  { goodsId: 'G003', orderNo: 'O20240614005', orderStatus: '已完成', member: '小明/1005', exchangeTime: '2024-06-14 11:10', quantity: 1 },
  { goodsId: 'G001', orderNo: 'O20240615006', orderStatus: '已完成', member: '小红/1006', exchangeTime: '2024-06-15 13:00', quantity: 1 },
  { goodsId: 'G001', orderNo: 'O20240616007', orderStatus: '已取消', member: '小刚/1007', exchangeTime: '2024-06-16 15:30', quantity: 1 },
  { goodsId: 'G002', orderNo: 'O20240617008', orderStatus: '待发货', member: '小美/1008', exchangeTime: '2024-06-17 09:00', quantity: 1 }
]
const recordDialog = reactive({
  visible: false,
  goodsId: '',
  tableData: [] as any[],
  page: { current: 1, size: 5, total: 0 }
})
function openRecordDialog(row: Record<string, any>) {
  recordDialog.goodsId = row.id
  recordDialog.visible = true
  recordDialog.page.current = 1
  loadRecordPage()
}
function loadRecordPage() {
  const all = mockRecords.filter(r => r.goodsId === recordDialog.goodsId)
  recordDialog.page.total = all.length
  const start = (recordDialog.page.current - 1) * recordDialog.page.size
  recordDialog.tableData = all.slice(start, start + recordDialog.page.size)
}

const orderDialog = reactive({ visible: false, data: null as any })
function openOrderDialog(row: any) {
  orderDialog.data = { ...row }
  orderDialog.visible = true
}
</script>

<style scoped>
.points-goods { padding: 32px; }
.header { display: flex; gap: 12px; align-items: center; margin-bottom: 12px; }
.filter-bar { margin-bottom: 16px; }
.filter-actions-row { margin-top: 8px; display: flex; gap: 12px; }
</style> 